package com.weixin.gong.example.jdk.bean;

import org.junit.Test;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * Created at 2017/10/11 10:38
 *
 * @author gongweixin
 */
public class SynchronizedExample {

    //synchronized修饰对象方法，锁在this对象上，所有synchronized修饰的对象方法互斥
    //synchronized修饰类方法，锁在class对象上，所有synchronized修饰的类方法互斥
    @Test
    public void testToString() throws InterruptedException {
        ExecutorService executor = Executors.newCachedThreadPool();
        final A a = new A();
        executor.execute(new Runnable() {
            public void run() {
                try {
                    a.a();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        executor.execute(new Runnable() {
            public void run() {
                try {
                    a.b();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        executor.execute(new Runnable() {
            public void run() {
                try {
                    new  A().a();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        executor.shutdown();
        while (!executor.awaitTermination(1, TimeUnit.SECONDS)) {

        }
    }

    static class A {
        synchronized void a() throws InterruptedException {
            Thread.sleep(1000);
            System.out.println("a");
        }

        synchronized void b() throws InterruptedException {
            Thread.sleep(1000);
            System.out.println("b");
        }
    }
}
